//
//  DCDispatchController.m
//  JiuyaoMotorcade
//
//  Created by 大橙子 on 2018/11/28.
//  Copyright © 2018 Tomous. All rights reserved.
//

#import "DCDispatchController.h"
#import "DCDispatchTableViewCell.h"
#import "DCDispatchModel.h"
#import "DCOrderDetailViewController.h"
#import "DCProgressHUDTool.h"
#import "DCCarrierModel.h"
#define bottomViewHeight 40
@interface DCDispatchController ()<UITableViewDelegate,UITableViewDataSource,dispatchTableViewCellDelegate>
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic, strong)UIView *bottomView;
@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,assign) NSInteger page;

@property (nonatomic,strong) NSMutableArray *selectedArr;
@end

@implementation DCDispatchController
-(NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
-(NSMutableArray *)selectedArr {
    if (!_selectedArr) {
        _selectedArr = [NSMutableArray array];
    }
    return _selectedArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self getDispatchData];
}
-(void)getDispatchData {
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[@"page"] = @"1";
    info[@"limit"] = @"8";
    __weak typeof(self) weakself = self;
    [DCServiceTool postWithUrl:getPagerTasksByCarrier01_URL params:info success:^(id responseObject) {
        DCLog(@"responseObject--%@",responseObject);
        if ([responseObject[@"code"] integerValue] == 0) {
            if ([responseObject[@"count"] integerValue] != 0) {
                [weakself.dataSource removeAllObjects];
                weakself.dataSource = [DCDispatchModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
                [weakself.view addSubview:weakself.bottomView];
                [weakself.view addSubview:weakself.tableView];
                [weakself.tableView reloadData];
                
//                [NOTIFICATION postNotificationName:@"1234567890" object:nil userInfo:@{@"diaoduCount":responseObject[@"count"]}];
                [weakself setUpBgViewIsShow:NO block:nil];
                weakself.page = [responseObject[@"page"] integerValue] + 1;
            }else{
                [weakself setUpBgViewIsShow:YES block:^{
                    [weakself getDispatchData];
                }];
            }
           
        }else {
            [weakself showMessage:responseObject[@"msg"] afterDelay:1.0];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height - bottomViewHeight, self.view.width, bottomViewHeight)];
        _bottomView.backgroundColor = [UIColor whiteColor];
        _bottomView.userInteractionEnabled = YES;
        
        __weak typeof(self) weakself = self;
        UIButton *appointBtn = [[UIButton alloc]init];
        [appointBtn setTitle:@"指派运力" forState:UIControlStateNormal];
        [appointBtn addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        appointBtn.tag = 2;
        appointBtn.titleLabel.font = FONT(15);
        appointBtn.layer.cornerRadius = 17;
        appointBtn.layer.borderColor = BlueColor.CGColor;
        appointBtn.layer.borderWidth = 1;
        [appointBtn setTitleColor:BlueColor forState:UIControlStateNormal];
        appointBtn.clipsToBounds = YES;
        [self.bottomView addSubview:appointBtn];
        [appointBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(weakself.bottomView).offset(-5);
            make.top.equalTo(weakself.bottomView).offset(3);
            make.bottom.equalTo(weakself.bottomView).offset(-3);
            make.width.mas_offset(80*WIDTHSCALE6);
        }];
        
        UIButton *carrierBtn = [[UIButton alloc]init];
        
        [carrierBtn setTitle:@"指派承运商" forState:UIControlStateNormal];
        [carrierBtn addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        carrierBtn.tag = 1;
        carrierBtn.titleLabel.font = FONT(15);
        carrierBtn.layer.cornerRadius = 17;
        carrierBtn.layer.borderColor = BlueColor.CGColor;
        carrierBtn.layer.borderWidth = 1;
        [carrierBtn setTitleColor:BlueColor forState:UIControlStateNormal];
        carrierBtn.clipsToBounds = YES;
        [self.bottomView addSubview:carrierBtn];
        [carrierBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(appointBtn.mas_left).offset(-10);
            make.top.equalTo(weakself.bottomView).offset(3);
            make.bottom.equalTo(weakself.bottomView).offset(-3);
            make.width.mas_offset(90*WIDTHSCALE6);
        }];
        
        UIButton *marketBtn = [[UIButton alloc]init];
        [marketBtn setTitle:@"发布交易市场" forState:UIControlStateNormal];
        [marketBtn addTarget:self action:@selector(buttonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        marketBtn.tag = 0;
        marketBtn.titleLabel.font = FONT(15);
        marketBtn.layer.cornerRadius = 17;
        marketBtn.layer.borderColor = BlueColor.CGColor;
        marketBtn.layer.borderWidth = 1;
        [marketBtn setTitleColor:BlueColor forState:UIControlStateNormal];
        marketBtn.clipsToBounds = YES;
        [self.bottomView addSubview:marketBtn];
        [marketBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(carrierBtn.mas_left).offset(-10);
            make.top.equalTo(weakself.bottomView).offset(3);
            make.bottom.equalTo(weakself.bottomView).offset(-3);
            make.width.mas_offset(110*WIDTHSCALE6);
        }];
    }
    return _bottomView;
}
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - bottomViewHeight) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellStyleDefault;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(reloadDispatchData)];
        _tableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMoeData)];
    }
    return _tableView;
}
-(void)reloadDispatchData {
    [self.tableView.mj_header endRefreshing];
    [self.selectedArr removeAllObjects];
    [self getDispatchData];
}
-(void)reloadMoeData {
    
    [self.tableView.mj_footer endRefreshing];
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[@"page"] = @(self.page);
    info[@"limit"] = @"5";
    __weak typeof(self) weakself = self;
    [DCServiceTool postWithUrl:getPagerTasksByCarrier01_URL params:info success:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            DCLog(@"responseObject--%@",responseObject);
            NSArray *array = [DCDispatchModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            if (array.count) {
                [weakself.dataSource addObjectsFromArray:array];
                [weakself.tableView reloadData];
                weakself.page = [responseObject[@"page"] integerValue] + 1;
            }else{
                [weakself showMessage:@"已加载全部数据" afterDelay:1.0];
            }
            
        }else {
            [weakself showMessage:responseObject[@"msg"] afterDelay:1.0];
        }
    } failure:^(NSError *error) {
        
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    DCDispatchTableViewCell *cell = [DCDispatchTableViewCell cellWithTableView:tableView];
    NSString *CellID = [NSString stringWithFormat:@"%ld-Cell",indexPath.row];
    DCDispatchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (cell == nil) {
        cell = [[DCDispatchTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = BackgroundColor;
    }
    cell.selectedBtn.tag = indexPath.row;
    cell.model = self.dataSource[indexPath.row];
    cell.delegate = self;
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (kBaseHeight-10)*3+kBaseHeight+10+3;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DCDispatchModel *model = self.dataSource[indexPath.row];
    DCOrderDetailViewController *detailVC = [[DCOrderDetailViewController alloc]initWithOrderID:model.ID state:@"待调度"];
    [[UIViewController currentViewController].navigationController pushViewController:detailVC animated:YES];
}
#pragma dispatchTableViewCellDelegate
-(void)selectedTableViewCell:(DCDispatchTableViewCell *)cell selectedAgreeRow:(NSInteger)row
{
    DCDispatchModel *model = self.dataSource[row];
    if (cell.selectedBtn.selected == YES) {
        [self.selectedArr addObject:model.ID];
    }else{
        [self.selectedArr removeObject:model.ID];
    }
}

-(void)buttonDidClick:(UIButton *)button
{
    if (self.selectedArr.count == 0) {
        [self showMessage:@"请至少选择一个订单" afterDelay:1.0];
        return;
    }
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    __weak typeof(self) weakself = self;
    if (button.tag == 0) {
        DCLog(@"发布交易市场");
        if (self.selectedArr.count > 1) {
            [self showMessage:@"请最多选择一个订单" afterDelay:1.0];
            return;
        }
        DCLog(@"self.selectedArr--%@",self.selectedArr);
        NSArray *array = @[
                           @{
                               @"VIN":@"VINDEDGDG245215123",
                               @"type":@"悦动",
                               @"color":@"黑"
                               },
                           @{
                               @"VIN":@"VINNDEDGDG24521124",
                               @"type":@"悦动",
                               @"color":@"黑"
                               },
                           @{
                               @"VIN":@"VINNDEDGDG24521125",
                               @"type":@"悦动",
                               @"color":@"黑"
                               },
                           @{
                               @"VIN":@"VINNDEDGDG24521126",
                               @"type":@"悦动",
                               @"color":@"黑"
                               },
                           @{
                               @"VIN":@"VINNDEDGDG24521127",
                               @"type":@"悦动",
                               @"color":@"黑"
                               },
                           @{
                               @"VIN":@"VINNDEDGDG24521128",
                               @"type":@"悦动",
                               @"color":@"黑"
                               },
                           ];
        NSMutableArray *arr = [DCDispatchModel mj_objectArrayWithKeyValuesArray:array];
        [[UIApplication sharedApplication].keyWindow addSubview:[[DCProgressHUDTool sharedHUDTool] showProgressWithType:0 datasource:arr title:@"提示" context:@"请选择发布至交易市场的车辆" sureBlock:^(NSString * _Nullable text, NSMutableArray * __nullable chooseArr) {
            DCLog(@"%@--%@",text,chooseArr);
        } cancleBlock:^(id  _Nonnull sender) {
            
        }]];
        
    }else if (button.tag == 1){
        DCLog(@"指派承运商");
        [DCServiceTool postWithUrl:getUnderCmpCarrier_URL params:info success:^(id responseObject) {
            if ([responseObject[@"code"] integerValue] == 0) {
                NSMutableArray *arr = [DCCarrierModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
                [[UIApplication sharedApplication].keyWindow addSubview:[[DCProgressHUDTool sharedHUDTool] showProgressWithType:1 datasource:arr title:@"指派承运商" context:@"请选择下派的承运商" sureBlock:^(NSString * _Nullable text, NSMutableArray * __nullable chooseArr) {
                    DCLog(@"%@--%@",text,chooseArr);
                    [weakself assignCarrierWithCarrierID:text];
                } cancleBlock:^(id  _Nonnull sender) {

                }]];
            }else{
                [weakself showError:@"获取承运商信息失败"];
            }
        } failure:^(NSError *error) {
            
        }];
        
        
    }else{
        DCLog(@"指派运力");
        NSArray *arr = @[
                         @{
                             @"driverName":@"张一",
                             @"plateNum":@"京A11111",
                             },
                         @{
                             @"driverName":@"张二",
                             @"plateNum":@"京A22222",
                             },
                         @{
                             @"driverName":@"张三",
                             @"plateNum":@"京A33333",
                             },
                         @{
                             @"driverName":@"张四",
                             @"plateNum":@"京A44444",
                             },
                         @{
                             @"driverName":@"张五",
                             @"plateNum":@"京A55555",
                             },
                         @{
                             @"driverName":@"张六",
                             @"plateNum":@"京A66666",
                             },
                         @{
                             @"driverName":@"张七",
                             @"plateNum":@"京A77777",
                             },
                         ];
        //        NSMutableArray *array = [DCDispatchModel mj_objectArrayWithKeyValuesArray:arr];
        NSMutableArray *array = [NSMutableArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
        [[UIApplication sharedApplication].keyWindow addSubview:[[DCProgressHUDTool sharedHUDTool] showProgressWithType:2 datasource:array title:@"指派运力" context:@"请选择车辆和司机" sureBlock:^(NSString * _Nullable text, NSMutableArray * _Nullable chooseArr) {
            DCLog(@"%@--%@",text,chooseArr);
        } cancleBlock:^(id  _Nonnull sender) {
            
        }]];
        
    }
}

#pragma 指派承运商
-(void)assignCarrierWithCarrierID:(NSString *)carrierID {
    
    __weak typeof(self) weakself = self;
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[@"orderIds[]"] = self.selectedArr;
    info[@"carrierId"] = carrierID;
    [DCServiceTool postWithUrl:assignCarrier_URL params:info success:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            [weakself showMessage:@"指派成功" afterDelay:1.0];
//            [weakself.selectedArr removeAllObjects];
            [weakself reloadDispatchData];
            [NOTIFICATION postNotificationName:@"refreshTaskTotalNum" object:nil];
        }else{
            [weakself showError:responseObject[@"msg"]];
        }
    } failure:^(NSError *error) {
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
